<?php

namespace app\admin\controller\vxpay;

use app\common\controller\Backend;
use think\Db;
/**
 * 微信支付
 */
class Pay extends Backend
{
    
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    
    
    public function _initialize()
    {
        $this->appid = "wx34e9c1335f650c07";
        $this->appsecret = "d41c9d86a8ccccb0667683d5cfdfc288";
        $this->mchid = '1618926160';
        include_once realpath(__DIR__ ."/../../../../addons/vxpay/example/WxPay.JsApiPay.php");
    }
    
    public function test(){
        $id = 369;
        $pay_order = DB::name("order")->where("id",$id)->find();
        $this->view->assign('pay_order', $pay_order);
        return $this->view->fetch();
    }
    
    public function jsapipay(){
        $tools = new \JsApiPay();
    	$openId = $tools->GetOpenid();
        $id = $_GET['id'];
        $str = $_GET['str'];
        $info = DB::name("order_prepare")->where("rand",$str)->order("id desc")->find();
        $time = strtotime($info['create_time']);
        if(time()-$time > 3){
            return $this->view->fetch("expire");
        }
    	//②、统一下单
    	$type_v = $_GET['type_v'];
    	if($type_v == 1){
    	    $pay_order = DB::name("order")->where("id",$id)->find();
    	    $v_order = 1;
    	}else{
    	    $pay_order = DB::name("reorder")->where("id",$id)->find();
    	    $v_order = 2;
    	}
    	$input = new \WxPayUnifiedOrder();
    	$input->SetBody("test");
    	$input->SetAttach("test");
    	$input->SetOut_trade_no("jsapi".$pay_order['order_sn']);
    // 	$money = $pay_order['amount'];
    	$money = 0.01;
    	$input->SetTotal_fee($money*100);
    	$input->SetTime_start(date("YmdHis"));
    	$input->SetTime_expire(date("YmdHis", time() + 600));
    	$input->SetGoods_tag("test");
    	$input->SetNotify_url("https://ceshi.780g.com/api/vxnotify/index");
    	$input->SetTrade_type("JSAPI");
    	$input->SetOpenid($openId);
    	$config = new \WxPayConfig();
    	$order = \WxPayApi::unifiedOrder($config, $input);
    	if($order['result_code'] != "SUCCESS"){
    	    $this->error($order['err_code_des']);
    	}
    	$jsApiParameters = $tools->GetJsApiParameters($order);
    	//获取共享收货地址js函数参数
	    $editAddress = $tools->GetEditAddressParameters();
    	$this->view->assign('jsApiParameters', $jsApiParameters);
    	$this->view->assign('editAddress', $editAddress);
    	$this->view->assign('money', $money);
    	$this->view->assign('pay_order', $pay_order);
    	$this->view->assign('v_order', $v_order);
    	
        return $this->view->fetch();
    }
    
    public function check_outtrade(){
        $trade = $_GET['trade'];
        $v_type = $_GET['v_type'];
        if($v_type == 1){
            $info = DB::name("order")->where("order_sn",$trade)->field("status")->find();
            if($info['status'] == 2 || $info['status'] == 11){
                $code = 1;
            }else{
                $code = 0;
            }
        }else{
            $info = DB::name("reorder")->where("order_sn",$trade)->field("status")->find();
            if($info['status'] == 2){
                $code = 1;
            }else{
                $code = 0;
            }
        }
        
        $data = array(
            'code'=>$code    
        );
        echo json_encode($data);die; 
    }
    
    public function get_jsapi(){
        // 获取token
        // $token_data = file_get_contents('./wechat_token.txt');
        // if (!empty($token_data)) {
        //     $token_data = json_decode($token_data, true);
        // }
        
        // $time  = time() - $token_data['time'];
        // if ($time > 3600) {
            $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $token_res = $this->https_request($token_url);
            $token_res = json_decode($token_res, true);
            $token = $token_res['access_token'];
        
            $data = array(
                'time' =>time(),
                'token' =>$token
            );
            $res = file_put_contents('./wechat_token.txt', json_encode($data));
            if ($res) {
                echo '更新 token 成功';
            }
        // } else {
        //     $token = $token_data['token'];
        // }
        
        // if ($time > 3600) {
            $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
            $ticket_res = $this->https_request($ticket_url);
            $ticket_res = json_decode($ticket_res, true);
            $ticket = $ticket_res['ticket'];
         
            $data = array(
                'time'    =>time(),
                'ticket'  =>$ticket
            );
            $res = file_put_contents('./wechat_ticket.txt', json_encode($data));
            if ($res) {
                echo '更新 ticket 成功';
            }
        // } else {
        //     $ticket = $ticket_data['ticket'];
        // }
        // 进行sha1签名
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        
        // 注意 URL 建议动态获取(也可以写死).
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 调用JSSDK的页面地址
        // $url = $_SERVER['HTTP_REFERER']; // 前后端分离的, 获取请求地址(此值不准确时可以通过其他方式解决)
         
        $str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
        $sha_str = sha1($str);
        
        
    }
    
    public function refund($out_trade_no,$total_fee,$refund_fee){
        include_once realpath(__DIR__ ."/../../../../addons/vxpay/lib/WxPay.Api.php");
        include_once realpath(__DIR__ ."/../../../../addons/vxpay/example/WxPay.Config.php");
        // $_REQUEST["out_trade_no"]= "jsapi2022010755739065810";
        // $_REQUEST["total_fee"]= "1";
        // $_REQUEST["refund_fee"] = "1";
        	try{
        // 		$out_trade_no = "jsapi20220550012499849712";
        // 		$total_fee = "1";
        // 		$refund_fee = "1";
                $out_trade_no = "jsapi".$out_trade_no;
                $total_fee = "1";
        		$refund_fee = "1";
        		$input = new \WxPayRefund();
        		$input->SetOut_trade_no($out_trade_no);
        		$input->SetTotal_fee($total_fee);
        		$input->SetRefund_fee($refund_fee);
        		$config = new \WxPayConfig();
        	    $input->SetOut_refund_no("sdkphp".date("YmdHis"));
        	    $input->SetOp_user_id($config->GetMerchantId());
        	    $result = \WxPayApi::refund($config, $input);
        	    return $result;
        // 		printf_info(WxPayApi::refund($config, $input));
        	} catch(Exception $e) {
        		Log::ERROR(json_encode($e));
        	}
        	exit();
        
    }
    
    function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 模拟 http 请求
     * @param  String $url  请求网址
     * @param  Array  $data 数据
     */
    function https_request($url, $data = null){
        // curl 初始化
        $curl = curl_init();
        $header = ['User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)','accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9']; //设置一个你的浏览器agent的header
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        // curl 设置
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    
        // 判断 $data get  or post
        if ( !empty($data) ) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    
        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}